package com.neusoft.neuiotms.dcam.fixed.converter;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.common.constant.AHConstants;
import com.neusoft.neuiotms.dcam.fixed.dto.AhAssetCardDTO;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetDTO;
import com.neusoft.neuiotms.dcam.fixed.model.AhAssetCard;
import com.neusoft.neuiotms.dcam.fixed.model.Asset;
import com.neusoft.neuiotms.dcam.fixed.repository.AhAssetCardRepository;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetRepository;
import com.neusoft.neuiotms.dcam.fixed.vo.AhAssetCardExportVO;

@Component
public class AhAssetCardConverter extends AbstractConverter<AhAssetCard, AhAssetCardDTO> {

    @Autowired
    private AhAssetCardRepository ahAssetCardRepository;
    @Autowired
    private AssetRepository assetRepository;
    @Autowired
    private AssetConverter assetConverter;

    @Override
    public AhAssetCard toModel(final AhAssetCardDTO dto) {
        AhAssetCard model;
        if (dto.isNew()) {
            model = new AhAssetCard();
        } else {
            model = this.ahAssetCardRepository.getOne(dto.getId());
        }
        model.setCode(dto.getCode());
        model.setDescription(dto.getDescription());
        model.setAmount(dto.getAmount());

        return model;
    }

    @Override
    public AhAssetCardDTO toDTO(final AhAssetCard model, final boolean forListView) {
        final AhAssetCardDTO dto = new AhAssetCardDTO();
        dto.setId(model.getId());
        dto.setCode(model.getCode());
        dto.setDescription(model.getDescription());
        dto.setAmount(model.getAmount());
        dto.setAmountinfact(
                this.assetRepository.countByOriginalCodeAndBelongs(model.getCode(), AHConstants.BELONG_SL_CODE));
        if (!forListView) {
            final List<Asset> assets =
                    this.assetRepository.findByOriginalCodeAndBelongs(model.getCode(), AHConstants.BELONG_SL_CODE);
            final List<AssetDTO> list = this.assetConverter.toListDTO(assets);
            dto.setAssets(list);
        }
        return dto;
    }

    public AhAssetCardExportVO toVO(final AhAssetCard model) {
        final AhAssetCardExportVO vo = new AhAssetCardExportVO();
        vo.setCode(model.getCode());
        vo.setDescription(model.getDescription());
        vo.setAmount(model.getAmount());
        vo.setAmountinfact(
                this.assetRepository.countByOriginalCodeAndBelongs(model.getCode(), AHConstants.BELONG_SL_CODE));
        return vo;

    }

}
